﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 死锁
{
  public  class AccountManager
    {
        private Account _fromAccount;

        private Account _toAccount;

        private double _amountToTransfer;


        public AccountManager(Account fromAccount, Account toAccount, double amount)

        {

            this._fromAccount = fromAccount;

            this._toAccount = toAccount;

            this._amountToTransfer = _amountToTransfer;

        }


        //转账

        public void Transfer()

        {

            Console.WriteLine(Thread.CurrentThread.Name + "正在" + _fromAccount.ID.ToString() + "获取锁");

            lock (_fromAccount)

            {

                Console.WriteLine(Thread.CurrentThread.Name + "已经" + _fromAccount.ID.ToString() + "获取到锁");

                Console.WriteLine(Thread.CurrentThread.Name + "被阻塞1秒");

                //模拟处理时间

                Thread.Sleep(1000);

                Console.WriteLine(Thread.CurrentThread.Name + "醒了，想想获取" + _toAccount.ID.ToString() + "的锁");

                lock (_toAccount)

                {

                    Console.WriteLine("如果造成线程死锁，这里的代码就不执行了~~");

                    _fromAccount.Withdraw(_amountToTransfer);

                    _toAccount.Deposit(_amountToTransfer);

                }

            }

        }


    }
}
